import { reactive } from 'vue';
import _ from 'lodash';
import * as Store from '@/store';
import dataList, { toolType } from '@/store/modules/processHeader/dataList';
import { getRandomString } from '@/utils/utils';
import * as Api from "@/api/processClient/processClient";
import type * as ApiType from '@/api/processClient/processClient.d';
import type * as PageType from '@/views/processClient/index.d';
import type * as PHStoreType from '@/store/modules/processHeader/type';
import type * as PDStoreType from '@/store/modules/processData/type';

/**
 * 数据适配器，用于将返回的不同的数据结构转换为页面相同展示的数据结构
 * @param resList {ApiType.SeriesResultResponse & ApiType.SeriesNameResponse} 整合的结果数据
 * @param type {boolean} 当前项目类型 为true是鉴影 为false是融影
 * @returns 无返回
 */
let glboalStr: string = '';
export const getDataMap = (
  resList: ApiType.SeriesResultResponse &
    ApiType.SeriesNameResponse &
    PDStoreType.ResList,
  type: boolean = false,
  index: number
) => {
  // 鉴影数据转换逻辑
  if (type) {
    // 存储当前序列号
    glboalStr = resList.series;
    // 创建工具类型的map
    const toolMap = new Map<string, ApiType.AuditLesionVoList[]>();
    // 创建工具名称字典
    const lesionEnum: { [x: string]: string } = {};
    // 创建病灶对应的小征象字典Map
    const lesionMap = new Map<
      string,
      {
        signForm: PHStoreType.Sign;
        compList: PHStoreType.Component[];
      }
    >();
    // 创建工具类型集合
    resList.auditTaskToolTypeList &&
      (resList.auditTaskToolTypeList = [
        ...new Set(resList.auditTaskToolTypeList),
      ]);
    // 根据病灶集合处理数据转换成工具类型的map
    resList.auditTaskToolTypeList &&
      resList.auditTaskToolTypeList.map((item) => {
        resList.auditLesionVoList &&
          resList.auditLesionVoList.map((it) => {
            lesionEnum[it.lesion] = it.lesionName;
            let resultArr: PHStoreType.Component[] = [];
            let signForm = _.cloneDeep({
              formId: 0,
              form: {},
              formOptions: [],
            });
            resultArr = it.taskToolComponentList && it.taskToolComponentList.map((t) => {
              getComponentsData(t, signForm);
              return changeLesionForComp(t);
            });
            lesionMap.set(
              it.lesion,
              _.cloneDeep({
                signForm,
                compList: resultArr,
              })
            );
            if (item !== '') {
              const tempArr = it.toolType.split(',');
              if (tempArr.includes(item)) {
                let list = toolMap.get(item);
                if (!list) {
                  list = [];
                  toolMap.set(item, list);
                }
                list.push(_.cloneDeep({ ...it, toolType: item }));
              }
            }
          });
      });

    // 创建标注医生大征象结果map
    const doctorScrMap = new Map();
    // 根据标注医生的大征象结果转换成征象map
    resList.annoDoctorScrList &&
      resList.annoDoctorScrList.map((item) => {
        let list = doctorScrMap.get(item.componentId);
        if (!list) {
          list = [];
          doctorScrMap.set(item.componentId, list);
        }
        list.push(_.cloneDeep(item));
      });

    // 创建大征象组件map
    const seriesCompMap = new Map();
    // 根据大征象组件设置的数据转换成大征象组件map
    resList.seriesComponentList &&
      resList.seriesComponentList.map((item) => {
        seriesCompMap.set(item.formComponentId, item);
      });

    // 创建小征象配置map
    const samllSignMap = new Map<number, ApiType.DataTaskToolComponentList>();
    // 去重处理
    const res = new Map();
    resList.taskToolComponentList &&
      (resList.taskToolComponentList = resList.taskToolComponentList.filter(
        (item) =>
          !res.has(item.formComponentId) && res.set(item.formComponentId, item)
      ));
    // 根据审核任务小征象配置集合转换成小征象配置map
    resList.taskToolComponentList &&
      resList.taskToolComponentList.map((item) => {
        samllSignMap.set(item.formComponentId, item);
      });

    // 创建类型map用于区分病灶及标注医生
    const typeMap = new Map<
      number,
      Map<number, ApiType.AuditTaskImageResultList[]>
    >();
    // 创建标注医生id集合map
    const doctorIdMap = new Map();
    // 创建标注医生id集合
    let doctorIdList: number[] = [];
    // 组id聚合的字典
    const imageGroupMap = new Map<number, ApiType.AuditTaskImageResultList[]>();
    // 根据审核病灶结果信息列表转换成类型map
    resList.auditTaskImageResultList &&
      (resList.auditTaskImageResultList = resList.auditTaskImageResultList.sort(
        (a, b) => a.consistencyType - b.consistencyType
      ));
    resList.auditTaskImageResultList &&
      resList.auditTaskImageResultList.map((item) => {
        // 根据类型处理map
        let list = typeMap.get(item.consistencyType);
        if (!list) {
          list = new Map<number, ApiType.AuditTaskImageResultList[]>();
          typeMap.set(item.consistencyType, list);
        }
        // 根据病灶组id处理map
        let listGroup = list.get(item.imageGroupId);
        if (!listGroup) {
          listGroup = [];
          list.set(item.imageGroupId, listGroup);
        }
        listGroup.push(_.cloneDeep({ ...item }));
        // 根据医生id处理map
        !doctorIdMap.has(item.doctorId && !item.goldStandard) &&
          doctorIdMap.set(item.doctorId, 1);
        // 保存组id聚合的字典
        let groupList = imageGroupMap.get(item.imageGroupId);
        if (!groupList) {
          groupList = [];
          imageGroupMap.set(item.imageGroupId, groupList);
        }
        groupList.push(_.cloneDeep({ ...item }));
      });
    // 医生id数组
    doctorIdList = [...doctorIdMap.keys()];
    // 医生id集合排序
    doctorIdList = doctorIdList.sort((a, b) => a - b);

    // 整体数据集合
    const dataList: PHStoreType.DataList[] = [];
    // 处理大征象数据
    const bigSignObj: PHStoreType.Sign = {
      form: {},
      formId: 0,
      formOptions: [],
    };
    [...seriesCompMap.values()].map((item) => {
      changeBigSign(item, bigSignObj, doctorScrMap, doctorIdList);
    });
    bigSignObj.formId = resList.series;
    // 针对大征象表单排序
    bigSignObj.formOptions.sort((a, b) => a.lesionType - b.lesionType);
    // 根据大征象类别判定是否需要将标注医生的数据保存
    saveBigSign(bigSignObj, resList.seriesComponentResultList, resList.sarIdList, index, resList.status);
    // 循环排序后结果
    let result: PHStoreType.Lesion[] = [] as PHStoreType.Lesion[];
    for (let index = 0; index < 4; index++) {
      result.push(
        _.cloneDeep({
          id: 0,
          isVisible: false,
          isAllVisible: true,
          lesionList: [] as PHStoreType.LesionListItem[][],
          viewList: [] as {
            lesionData: PHStoreType.LesionData;
            lesion: {
              signForm: PHStoreType.Sign;
              compList: PHStoreType.Component[];
            };
          }[],
        })
      );
    }

    // 循环类型map字典获取viewData
    typeMap.forEach((values, key) => {
      const imageGroupObj: { [x: number]: PHStoreType.LesionListItem[] } =
        _.cloneDeep({});
      let typeTempObj = _.cloneDeep({
        id: key,
        isVisible: false,
        isAllVisible: true,
        lesionList: [] as PHStoreType.LesionListItem[][],
        viewList: [] as {
          lesionData: PHStoreType.LesionData;
          lesion: {
            signForm: PHStoreType.Sign;
            compList: PHStoreType.Component[];
          };
        }[],
      });
      const tempArr: PHStoreType.LesionListItem[][] =
        [] as PHStoreType.LesionListItem[][];
      values.forEach((v, k) => {
        // 处理组list集合转换成viewModel数据结构
        let resultArr = changeLesion(v, lesionEnum, samllSignMap);
        imageGroupObj[k] = _.cloneDeep(resultArr);
        resultArr = _.orderBy(
          resultArr,
          ['goldStandard', 'doctorId'],
          ['asc', 'asc']
        );
        tempArr.push(_.cloneDeep(resultArr));
      });
      // typeTempObj.lesionList = [...tempArr, ...tempArr, ...tempArr];
      // typeTempObj.viewList = [...getLesionData(tempArr, lesionMap, doctorIdList, true), ...getLesionData(tempArr, lesionMap, doctorIdList, true), ...getLesionData(tempArr, lesionMap, doctorIdList, true)];
      typeTempObj.lesionList = tempArr;
      typeTempObj.viewList = getLesionData(tempArr, lesionMap, doctorIdList, true);
      result = result && result.map((item, index) => {
        if (index + 1 === key) {
          item = typeTempObj;
        }
        item.id = index + 1;
        return item;
      });
      // typeTempObj.lesionList.map(ite => {
      //   typeTempObj.viewList.map(it => {
      //     it = _.cloneDeep(resultForForm(ite, it));
      //   });
      // });
    });
    let lesionResultList: PHStoreType.Lesion[] = [] as PHStoreType.Lesion[];
    lesionResultList = result;
    lesionResultList[0].viewList = lesionResultList[0].viewList.map((it, index) => {
      it = resultForForm(lesionResultList[0].lesionList[index], it);
      return it;
    });
    lesionResultList[1].viewList = lesionResultList[1].viewList.map((it, index) => {
      it = resultForForm(lesionResultList[1].lesionList[index], it);
      return it;
    });
    lesionResultList[2].viewList = lesionResultList[2].viewList.map((it, index) => {
      it = resultForForm(lesionResultList[2].lesionList[index], it);
      return it;
    });
    lesionResultList[3].viewList = lesionResultList[3].viewList.map((it, index) => {
      it = resultForForm(lesionResultList[3].lesionList[index], it);
      return it;
    });
    // lesionResultList[0].lesionList.map(ite => {
    //   lesionResultList[0].viewList.map(it => {
    //     it = resultForForm(ite, it);
    //   });
    // });
    // lesionResultList[1].lesionList.map(ite => {
    //   lesionResultList[1].viewList.map(it => {
    //     it = resultForForm(ite, it);
    //   });
    // });
    // lesionResultList[2].lesionList.map(ite => {
    //   lesionResultList[2].viewList.map(it => {
    //     it = resultForForm(ite, it);
    //   });
    // });
    // lesionResultList[3].lesionList.map(ite => {
    //   lesionResultList[3].viewList.map(it => {
    //     it = resultForForm(ite, it);
    //   });
    // });
    // lesionResultList.map(item => {
    //   item.lesionList.map(ite => {
    //     item.viewList.map(it => {
    //       it = resultForForm(ite, it);
    //     });
    //   });
    // })
    // 根据整合的数据进行数据整体聚合转换成多序列下的整体数据map
    resList.seriesList &&
      resList.seriesList.map((item) => {
        const tempObj = {
          series: item,
          sarIdList: resList.sarIdList,
          seriesCompList: bigSignObj,
          children: [] as PHStoreType.Lesion[],
        };
        // 处理病灶及小征象
        tempObj.children = _.cloneDeep(result);
        dataList.push(tempObj);
      });

    // 工具列表渲染数据结合
    const toolListMap = new Map<
      string,
      Array<PHStoreType.ToolLesionItem & ApiType.AuditTaskImageResultList>
    >();
    // 根据工具map处理内部小征象数据
    toolMap.forEach((values, key) => {
      const tempArr = values && values.map((item) =>
        changeSettingsLesion(item, samllSignMap)
      );
      toolListMap.set(key, tempArr);
    });

    return {
      toolMap,
      doctorScrMap,
      seriesCompMap,
      samllSignMap,
      typeMap,
      doctorIdMap,
      doctorIdList,
      dataList,
      lesionEnum,
      toolListMap,
      lesionResultList,
      lesionMap,
      bigSignObj,
      imageGroupMap
    };
  }

  // 融影数据转换逻辑
  if (!type) {
  }
};

/**
 * 根据工具Map字典处理
 * @param item
 * @param samllSignMap
 * @returns
 */
export const changeSettingsLesion = (
  item: ApiType.AuditLesionVoList,
  samllSignMap: Map<number, ApiType.DataTaskToolComponentList>
) => {
  const {
    colour: color,
    lesion: code,
    lesionName: name,
    toolType: type,
    taskToolComponentList: comps,
  } = item;
  const tempArr = comps && comps.map((it) => {
    const temp = samllSignMap.get(it.formComponentId);
    // 将配置进行转换
    if (temp) {
      return changeComponent(temp, it);
    } else {
      return _.cloneDeep({
        result: '',
        formComponentId: 0,
        auditTaskComponentResultId: 0,
      });
    }
  });
  // 处理最终小征象数据
  // auditStatus => 1-未审核 2-已审核
  return _.cloneDeep({
    auditStatus: 1,
    compareDice: null,
    consistencyType: 4,
    derivativeId: null,
    doctorId: 0,
    expectResultType: 1,
    fileType: null,
    formComponentList: tempArr,
    goldStandard: true,
    imageAnnotationToolType: type,
    imageGroupId: 0,
    imageId: 0,
    imageResult: '',
    lesion: code,
    maskImgList: [],
    urlWan: null,
    name,
    color: '#f7bc5a',
    uuid: getRandomString(),
  });
};

/**
 * 改变病灶列表转换成组件
 * @param item 组件每一项
 * @returns 转换后数据
 */
export const changeLesionForComp = (
  item: ApiType.AuditLesionVoListTaskToolComponentList
) => {
  const {
    componentCode: code,
    componentData: data,
    componentParameter: parameter,
    componentName: name,
    componentType: type,
    formComponentId: id,
    required,
  } = item;
  return _.cloneDeep({
    id,
    name,
    type,
    options: _.cloneDeep(getOptionData(JSON.parse((data as string) || '[]'))),
    parameter: _.cloneDeep(JSON.parse(parameter || '{}')),
    required: required ?? false,
    formComponentId: id,
    result: '',
    auditTaskComponentResultId: 0,
  });
};

/**
 * 通过map字典变更大征象数据
 * @param item 接口中的每一项病灶
 * @param result 渲染结果
 * @param doctorScrMap 医生数据的map字典
 * @param doctorIdList 医生id数组
 */
export const changeBigSign = (
  item: ApiType.AuditLesionVoListTaskToolComponentList,
  result: PHStoreType.Sign,
  doctorScrMap: Map<any, any>,
  doctorIdList: number[]
) => {
  const {
    componentCode: code,
    componentName: name,
    componentType: cType,
    formComponentId: id,
    required,
    componentParameter: parameter,
    componentData: data,
  } = item;
  const tempFormObj = _.cloneDeep({
    id,
    name,
    type: cType,
    firstMarkUserId: 0,
    firstMarkContent: '',
    secondMarkUserId: 0,
    secondMarkContent: '',
    lesionType: 4,
    approveField: code,
    approveContent: '',
    required: required ?? false,
    parameter: _.cloneDeep(JSON.parse(parameter || '{}')),
    options: _.cloneDeep(getOptionData(JSON.parse((data as string) || '[]'))),
  });
  changeForm(cType, code, result);
  let tempArr: { componentId: number; userId: number; result: string }[] =
    doctorScrMap.get(id);
  if (tempArr) {
    if (tempArr.length === 0) {
      // 为类型4
      tempFormObj.lesionType = 4;
    };
    if (tempArr.length === 1) {
      // 为类型3
      tempFormObj.lesionType = 3;
      tempFormObj.firstMarkUserId = tempArr[0].userId;
      tempFormObj.approveContent = tempArr[0].result;
      tempFormObj.firstMarkContent = tempArr[0].result;
      let resultArr: string[] = []
      let arr: string[] = [];
      if (tempFormObj.type === 'checkbox') {
        if (tempArr[0].result.includes(',')) {
          resultArr = tempArr[0].result.split(',');
        } else {
          resultArr = [tempArr[0].result];
        };
        tempFormObj.options.length !== 0 && tempFormObj.options.map(item => {
          resultArr.map(it => {
            if (item.value === it) {
              arr.push(item.label);
            };
          });
        });
        tempFormObj.firstMarkContent = resultArr.join(',');
      };
      if (tempFormObj.type === 'child_select') {
        if (tempArr[0].result.includes('@#@')) {
          resultArr = tempArr[0].result.split('@#@');
        } else {
          resultArr = [tempArr[0].result];
        };
        tempFormObj.options.length !== 0 && tempFormObj.options.map(item => {
          resultArr.map(it => {
            if (item.value === it) {
              arr.push(item.label);
            };
          });
        });
        tempFormObj.firstMarkContent = resultArr.join(',');
      };
      if (tempFormObj.options && tempFormObj.options.length !== 0) {
        tempFormObj.options.map(item => {
          if (item.value === tempArr[0].result) {
            tempFormObj.firstMarkContent = item.label;
          }
        })
      };
    };
    if (tempArr.length === 2) {
      tempArr.sort((a, b) => a.userId - b.userId);
      // 为类型1或者2
      // 比对结果相同为1，不同为2
      if (tempArr[0].result === tempArr[1].result) {
        tempFormObj.lesionType = 1;
        tempFormObj.firstMarkUserId = tempArr[0].userId;
        tempFormObj.secondMarkUserId = tempArr[1].userId;
        tempFormObj.firstMarkContent = tempArr[0].result;
        tempFormObj.secondMarkContent = tempArr[1].result;
        tempFormObj.approveContent = tempArr[0].result;
        let resultArr1: string[] = [];
        let resultArr2: string[] = [];
        let arr1: string[] = [];
        let arr2: string[] = [];
        if (tempFormObj.type === 'checkbox') {
          if (tempArr[0].result.includes(',')) {
            resultArr1 = tempArr[0].result.split(',');
          } else {
            resultArr1 = [tempArr[0].result];
          };
          if (tempArr[1].result.includes(',')) {
            resultArr2 = tempArr[0].result.split(',');
          } else {
            resultArr2 = [tempArr[0].result];
          }
          tempFormObj.options.length !== 0 && tempFormObj.options.map(item => {
            resultArr1.map(it => {
              if (item.value === it) {
                arr1.push(item.label);
              };
            });
            resultArr2.map(it => {
              if (item.value === it) {
                arr2.push(item.label);
              };
            })
          });
          tempFormObj.firstMarkContent = arr1.join(',');
          tempFormObj.secondMarkContent = arr2.join(',');
        };
        if (tempFormObj.type === 'child_select') {
          if (tempArr[0].result.includes('@#@')) {
            resultArr1 = tempArr[0].result.split('@#@');
          } else {
            resultArr1 = [tempArr[0].result];
          };
          tempFormObj.options.length !== 0 && tempFormObj.options.map(item => {
            resultArr1.map(it => {
              if (item.value === it) {
                arr1.push(item.label);
              };
            });
          });
          tempFormObj.firstMarkContent = arr1.join(',');
        };
        if (tempFormObj.options && tempFormObj.options.length !== 0) {
          tempFormObj.options.map(item => {
            if (item.value === tempArr[0].result) {
              tempFormObj.firstMarkContent = item.label;
            };
            if (item.value === tempArr[1].result) {
              tempFormObj.secondMarkContent = item.label;
            };
          });
        };
      } else {
        tempFormObj.lesionType = 2;
        tempFormObj.firstMarkUserId = tempArr[0].userId;
        tempFormObj.secondMarkUserId = tempArr[1].userId;
        tempFormObj.firstMarkContent = tempArr[0].result;
        tempFormObj.secondMarkContent = tempArr[1].result;
        tempFormObj.approveContent = '';
        let resultArr1: string[] = [];
        let resultArr2: string[] = [];
        let arr1: string[] = [];
        let arr2: string[] = [];
        if (tempFormObj.type === 'checkbox') {
          if (tempArr[0].result.includes(',')) {
            resultArr1 = tempArr[0].result.split(',');
          } else {
            resultArr1 = [tempArr[0].result];
          };
          if (tempArr[1].result.includes(',')) {
            resultArr2 = tempArr[0].result.split(',');
          } else {
            resultArr2 = [tempArr[0].result];
          }
          tempFormObj.options.length !== 0 && tempFormObj.options.map(item => {
            resultArr1.map(it => {
              if (item.value === it) {
                arr1.push(item.label);
              };
            });
            resultArr2.map(it => {
              if (item.value === it) {
                arr2.push(item.label);
              };
            })
          });
          tempFormObj.firstMarkContent = arr1.join(',');
          tempFormObj.secondMarkContent = arr2.join(',');
        };
        if (tempFormObj.type === 'child_select') {
          if (tempArr[0].result.includes('@#@')) {
            resultArr1 = tempArr[0].result.split('@#@');
          } else {
            resultArr1 = [tempArr[0].result];
          };
          tempFormObj.options.length !== 0 && tempFormObj.options.map(item => {
            resultArr1.map(it => {
              if (item.value === it) {
                arr1.push(item.label);
              };
            });
          });
          tempFormObj.firstMarkContent = arr1.join(',');
        };
        if (tempFormObj.options && tempFormObj.options.length !== 0) {
          tempFormObj.options.map(item => {
            if (item.value === tempArr[0].result) {
              tempFormObj.firstMarkContent = item.label;
            };
            if (item.value === tempArr[1].result) {
              tempFormObj.secondMarkContent = item.label;
            };
          });
        };
      };
    };
  } else {
    tempFormObj.lesionType = 4;
  }
  result.formOptions.push(tempFormObj);
};

const saveBigSign = (signObj: PHStoreType.Sign, componentList: ApiType.AnnoDoctorScrList[], sarIdList: number[], index: number, status: number) => {
  // 根据标注医生回填数据
  if (componentList && componentList.length === 0) {
    // 需要回填数据
    signObj.formOptions.map(item => {
      if (item.lesionType === 1) {
        signObj.form[item.id] = item.approveContent;
        if (item.type === 'checkbox') {
          if (item.approveContent.includes(',')) {
            signObj.form[item.id] = item.approveContent.split(',');
          } else {
            signObj.form[item.id] = [item.approveContent];
          };
        };
        if (item.type === 'child_select') {
          if (item.approveContent.includes('@#@')) {
            signObj.form[item.id] = item.approveContent.split('@#@');
          } else {
            signObj.form[item.id] = [item.approveContent];
          };
        };
      };
      if (item.lesionType === 2) {
        if (item.firstMarkContent === item.secondMarkContent) {
          signObj.form[item.id] = item.approveContent;
          if (item.type === 'checkbox') {
            if (item.approveContent.includes(',')) {
              signObj.form[item.id] = item.approveContent.split(',');
            } else {
              signObj.form[item.id] = [item.approveContent];
            };
          };
          if (item.type === 'child_select') {
            if (item.approveContent.includes('@#@')) {
              signObj.form[item.id] = item.approveContent.split('@#@');
            } else {
              signObj.form[item.id] = [item.approveContent];
            };
          };
        };
      };
      if (item.lesionType === 3) {
        signObj.form[item.id] = item.approveContent;
        if (item.type === 'checkbox') {
          if (item.approveContent.includes(',')) {
            signObj.form[item.id] = item.approveContent.split(',');
          } else {
            signObj.form[item.id] = [item.approveContent];
          };
        };
        if (item.type === 'child_select') {
          if (item.approveContent.includes('@#@')) {
            signObj.form[item.id] = item.approveContent.split('@#@');
          } else {
            signObj.form[item.id] = [item.approveContent];
          };
        };
      };
    });
    // 调用保存征象接口
    if (status === 1) {
      saveSign(signObj, sarIdList, index);
    }
  };
  componentList && componentList.map(item => {
    signObj.formOptions.map(it => {
      if (it.id === item.componentId) {
        signObj.form[item.componentId] = item.result;
        if (it.type === 'checkbox') {
          if (item.result.includes(',')) {
            signObj.form[item.componentId] = item.result.split(',');
          } else {
            if (item.result !== '') {
              signObj.form[item.componentId] = [item.result];
            }
          };
        };
        if (it.type === 'child_select') {
          if (item.result.includes('@#@')) {
            signObj.form[item.componentId] = item.result.split('@#@');
          } else {
            if (item.result !== '') {
              signObj.form[item.componentId] = [item.result];
            }
          };
        };
      };
    });
  });
};

const saveSign = async (signObj: PHStoreType.Sign, sarIdList: number[], index: number) => {
  const params = {
    componentResultList: [] as {componentId: number, result: string}[],
    sarId: sarIdList[index]
  };
  params.componentResultList = signObj.formOptions.map(item => {
    let result = '';
    if (Array.isArray(signObj.form[item.id])) {
      if (item.type === 'checkbox') {
        result = (signObj.form[item.id] as string[]).join(',');
      };
      if (item.type === 'child_select') {
        result = (signObj.form[item.id] as string[]).join('@#@');
      };
    } else {
      result = signObj.form[item.id] as string;
    };
    return {
      componentId: item.id,
      result
    };
  });
  const result = await Api.saveBigSign(params);
  if (result.data) {
    signObj.form = _.cloneDeep({
      ...signObj.form,
    });
  };
};

/**
 * 根据审核病灶信息列表转换工具函数
 * @param dataList 原始数据，转成Map的数据字典
 * @param lesionEnum 病灶字典，用于将病灶code转换成name文本
 * @param samllSignMap 小征象数据map
 * @returns 转换后的组id的数据集合
 */
export const changeLesion = (
  dataList: ApiType.AuditTaskImageResultList[],
  lesionEnum: { [x: string]: string },
  samllSignMap: Map<number, ApiType.DataTaskToolComponentList>
) => {
  const imageGroupList = dataList && dataList.map((item) => {
    // 创建最终展示数据集合
    const arr = item.formComponentList && item.formComponentList.map((it) => {
      const temp = samllSignMap.get(it.formComponentId);
      // 将配置进行转换
      if (temp) {
        return changeComponent(temp, it);
      } else {
        return _.cloneDeep({
          result: '',
          formComponentId: 0,
          auditTaskComponentResultId: 0,
        });
      }
    });
    // auditStatus => 1-未审核 2-已审核
    return _.cloneDeep({
      ...item,
      name: lesionEnum[item.lesion],
      imageResult:  item.imageResult.includes("{") ? JSON.parse(item.imageResult || '{}') : item.imageResult,
      formComponentList: arr,
      isCurrent: false,
      isEye: item.goldStandard,
      isApprove: item.auditStatus,
      className:
        item.goldStandard && item.consistencyType === 4 ? 'approve' : '',
      uuid: getRandomString(),
    }) as PHStoreType.LesionListItem;
  });
  return imageGroupList;
};

/**
 * 改变审核病灶结果列表小征象组件数据
 * @param componentList 通过配置map字典获取的每一项数据
 * @param item 组件数据的每一项数据
 * @returns 返回调整之后的配置数据
 */
export const changeComponent = (
  componentList: ApiType.DataTaskToolComponentList,
  item:
    | ApiType.FormComponentList
    | ApiType.AuditLesionVoListTaskToolComponentList
) => {
  const {
    componentCode: code,
    componentData: data,
    componentParameter: parameter,
    componentName: name,
    componentType: type,
    formComponentId: id,
    required,
  } = componentList;
  if ('result' in item) {
    return _.cloneDeep({
      id,
      name,
      type,
      options: _.cloneDeep(getOptionData(JSON.parse(data || '[]'))),
      parameter: _.cloneDeep(JSON.parse(parameter || '{}')),
      required: required ?? false,
      result: item.result ?? '',
      auditTaskComponentResultId: item.auditTaskComponentResultId ?? 0,
      formComponentId: id,
    });
  } else {
    return _.cloneDeep({
      id,
      name,
      type,
      options: _.cloneDeep(getOptionData(JSON.parse(data || '[]'))),
      parameter: _.cloneDeep(JSON.parse(parameter || '{}')),
      required: required ?? false,
      result: '',
      auditTaskComponentResultId: 0,
      formComponentId: id,
    });
  }
};

/**
 * 根据左侧列表处理过的数据集合转换成视图层的数据结果
 * @param dataList 左侧列表病灶数据集合
 * @returns 返回处理后的新数据数组对象
 */
export const getLesionData = (
  dataList: PHStoreType.LesionListItem[][],
  lesionMap: Map<
    string,
    {
      signForm: PHStoreType.Sign;
      compList: PHStoreType.Component[];
    }
  >,
  doctorIdList: number[],
  type: boolean = false
) => {
  let lesionData = _.cloneDeep({}) as PHStoreType.LesionData;
  const result = dataList && dataList.map((item) => {
    switch (item.length) {
      case 0:
        lesionData = _.cloneDeep({
          firstLesionCode: '',
          firstLesionName: '',
          firstLesionId: 0,
          firstMarkUserId: 0,
          secondLesionCode: '',
          secondLesionName: '',
          secondLesionId: 0,
          secondMarkUserId: 0,
          approveLeisonCode: '',
          approveLeisonName: '',
          approveLeisonId: 0,
          approveUserId: 0,
          toolType: '',
          uuid:  getRandomString(),
          color: '#f7bc5a',
          positionVal: 1,
          lesionType: 4,
          approveStatus: 1,
          imageResult: '',
          isApproveEye: true,
          isCurrent: false,
          className: 'approve',
          imageGroupId: 0,
        });
        break;
      case 1:
        lesionData = _.cloneDeep({
          firstLesionCode: '',
          firstLesionName: '',
          firstLesionId: 0,
          firstMarkUserId: 0,
          secondLesionCode: '',
          secondLesionName: '',
          secondLesionId: 0,
          secondMarkUserId: 0,
          approveLeisonCode: item[0].lesion,
          approveLeisonName: item[0].name,
          approveLeisonId: item[0].imageId,
          approveUserId: item[0].doctorId,
          toolType: item[0].imageAnnotationToolType,
          uuid: item[0].uuid || getRandomString(),
          color: '#f7bc5a',
          positionVal: item[0].expectResultType,
          lesionType: item[0].consistencyType,
          approveStatus: item[0].auditStatus ?? 1,
          imageResult: item[0].imageResult,
          isApproveEye: true,
          isCurrent: false,
          imageGroupId: item[0].imageGroupId,
          className:
            item[0].goldStandard && item[0].consistencyType === 4
              ? 'approve'
              : '',
        });
        break;
      case 2:
        lesionData = _.cloneDeep({
          firstLesionCode: item[0].lesion,
          firstLesionName: item[0].name,
          firstLesionId: item[0].imageId,
          firstMarkUserId: item[0].doctorId,
          secondLesionCode: '',
          secondLesionName: '',
          secondLesionId: 0,
          secondMarkUserId: 0,
          approveLeisonCode: item[1].lesion,
          approveLeisonName: item[1].name,
          approveLeisonId: item[1].imageId,
          approveUserId: item[1].doctorId,
          toolType: item[1].imageAnnotationToolType,
          uuid: item[1].uuid ||  getRandomString(),
          color: '#f7bc5a',
          positionVal: item[1].expectResultType,
          lesionType: item[1].consistencyType,
          approveStatus: item[1].auditStatus ?? 1,
          imageResult: item[1].imageResult,
          imageGroupId: item[1].imageGroupId,
          isApproveEye: true,
          isCurrent: false,
          className:
            item[1].goldStandard && item[1].consistencyType === 4
              ? 'approve'
              : '',
        });
        break;
      case 3:
        lesionData = _.cloneDeep({
          firstLesionCode: item[0].lesion,
          firstLesionName: item[0].name,
          firstLesionId: item[0].imageId,
          firstMarkUserId: item[0].doctorId,
          secondLesionCode: item[1].lesion,
          secondLesionName: item[1].name,
          secondLesionId: item[1].imageId,
          secondMarkUserId: item[1].doctorId,
          approveLeisonCode: item[2].lesion,
          approveLeisonName: item[2].name,
          approveLeisonId: item[2].imageId,
          approveUserId: item[2].doctorId,
          toolType: item[2].imageAnnotationToolType,
          uuid: item[2].uuid || getRandomString(),
          color: '#f7bc5a',
          positionVal: item[2].expectResultType,
          lesionType: item[2].consistencyType,
          approveStatus: item[2].auditStatus ?? 1,
          imageResult: item[2].imageResult,
          imageGroupId: item[2].imageGroupId,
          isApproveEye: true,
          isCurrent: false,
          className:
            item[2].goldStandard && item[2].consistencyType === 4
              ? 'approve'
              : '',
        });
        break;
      default:
        break;
    }
    const lesion = getCurrentSmallSign(lesionData, lesionMap, item, doctorIdList, type);
    return lesion;
  });
  return result;
};

/**
 * 将结果数据调整为页面数据
 * @param dataList 结果数据
 * @param viewList 页面数据
 */
export const getViewList = (
  dataList: PDStoreType.PrDataState,
  viewList: PageType.ViewData,
  route: any
) => {
  // 页面标题
  viewList.headerTitle = dataList.seriesNameResult.name;
  // 左侧病灶列表序列号
  viewList.seiesId = dataList.seriesResult.series;
  // 左侧病灶列表
  viewList.lesionList = dataList.lesionResultList;
  // 序列征象设置
  viewList.signForm = dataList.bigSignObj;
  // 处理阴阳性
  viewList.isShowYay = dataList.seriesResult.needYay;
  if (dataList.seriesResult.yay !== null) {
    viewList.yay = dataList.seriesResult.yay === 1 ? true : false;
  } else {
    viewList.yay = undefined;
  };
  // 处理查看数据
  if (route.query.type === 'view') {
    viewList.isShowYay = false;
    viewList.isReject = dataList.seriesResult.discardCode !== null && dataList.seriesResult.discardCode !== '';
    const tempArr = dataList.seriesResult.discardConfig && dataList.seriesResult.discardConfig.filter(item => item.value === dataList.seriesResult.discardCode);
    if (tempArr.length !== 0) {
      viewList.rejectValue = [tempArr[0].name, dataList.seriesResult.discardReason].join(' ');
    };
    viewList.isYay = dataList.seriesResult.yay !== null;
    dataList.seriesResult.yay !== null && (viewList.yayValue = dataList.seriesResult.yay === 2);
  };
};

/**
 * 处理Form表单数据工具函数
 * @param type 当前征象组件类型
 * @param code 当前征象组件code值
 * @param resultList 需要处理的数据结果 可选的
 */
const changeForm = (
  type: string,
  code: string | number,
  resultList?: PHStoreType.Sign
) => {
  if (resultList) {
    if (type === 'checkbox' || type === 'child_select') {
      resultList.form[code] = [];
    } else {
      resultList.form[code] = '';
    }
  }
};

/**
 * 处理表单的options集合数据
 * @param dataList 当前数据集合
 * @returns
 */
const getOptionData = (dataList: ApiType.ComponentData[]) => {
  if (!dataList) return [];
  let resultArr: PHStoreType.OptionsItem[] = [];
  resultArr = dataList && dataList.map((item) => {
    let obj = {
      value: '',
      label: '',
      children: null as unknown as PHStoreType.OptionsItem[],
    };
    if (item.child && item.child.length > 0) {
      obj.value = item.code;
      obj.label = item.text;
      obj.children = getOptionData(item.child);
    } else {
      obj.value = item.code;
      obj.label = item.text;
    }
    return obj;
  });
  return resultArr;
};

/**
 * 处理小征象组件数据
 * @param item 标注征象的每一项集合数据
 * @param type 处理当前征象配置的区分 true为序列征象（大征象）false为标注征象（小征象）
 * @param result 当前工具栏的挂载数据集合 可选
 */
const getComponentsData = (
  item: ApiType.AuditLesionVoListTaskToolComponentList,
  result: PHStoreType.Sign
) => {
  const {
    componentCode: code,
    componentName: name,
    componentType: cType,
    formComponentId: id,
    required,
    componentParameter: parameter,
    componentData: data,
  } = item;
  const tempObj = _.cloneDeep({
    id,
    name,
    type: cType,
    firstMarkUserId: 0,
    firstMarkContent: '',
    secondMarkUserId: 0,
    secondMarkContent: '',
    lesionType: 4,
    approveField: code,
    approveContent: '',
    required: required ?? false,
    parameter: _.cloneDeep(JSON.parse(parameter || '{}')),
    options: _.cloneDeep(getOptionData(JSON.parse((data as string) || '[]'))),
  });
  changeForm(cType, code, result);
  result.formOptions.push(tempObj);
};

/**
 * 点击左侧病灶列表获取小征象
 * @param item 当前点击的数据
 */
const getCurrentSmallSign = (
  lesionData: PHStoreType.LesionData,
  lesionMap: Map<
    string,
    {
      signForm: PHStoreType.Sign;
      compList: PHStoreType.Component[];
    }
  >,
  dataList: PHStoreType.LesionListItem[],
  doctorIdList: number[],
  type: boolean = false
) => {
  // 通过数据仓库中的病灶map和当前选择的审核病灶的code值得到当前的病灶数据
  const lesion = lesionMap.get(lesionData.approveLeisonCode) as {
    signForm: PHStoreType.Sign;
    compList: PHStoreType.Component[];
  };
  if (lesion) {
    lesion.signForm.formId = lesionData.imageGroupId;
    lesion.signForm.formOptions = lesion.signForm.formOptions && lesion.signForm.formOptions.map((it) => {
      it.lesionType = lesionData.lesionType;
      it.firstMarkUserId = lesionData.firstMarkUserId;
      it.secondMarkUserId = lesionData.secondMarkUserId;
      return it;
    });
    lesion.signForm = _.cloneDeep({
      ...lesion.signForm,
      lesionType: lesionData.lesionType,
      firstMarkUserId: lesionData.firstMarkUserId,
      secondMarkUserId: lesionData.secondMarkUserId,
      positionVal: lesionData.positionVal,
    });
  }
  return _.cloneDeep({
    lesionData,
    lesion,
  });
};

/**
 * 点击左边病灶列表并改变表单数据辅助工具函数
 * @param option 左边病灶列表点击的当前项
 * @param list 仓库数据的配置集合
 * @returns 返回处理后的当前项
 */
export const changeFormOption = (
  option: PHStoreType.FormItem,
  list: PHStoreType.LesionListItem[],
  form: { [x: string | number]: any },
  doctorIdList: number[]
) => {
  switch (list.length) {
    case 0:
      option = _.cloneDeep({
        ...option,
      });
      break;
    case 1:
      list[0].formComponentList.length !== 0 &&
        list[0].formComponentList.map((item) => {
          if (item.formComponentId === option.id) {
            let result: string | string[] = item.result;
            if (option.type === 'checkbox') {
              if (item.result.includes(',')) {
                result = item.result.split(',');
              } else {
                result = [item.result];
              }
            }
            if (option.type === 'child_select') {
              if (item.result.includes('@#@')) {
                result = item.result.split('@#@');
              } else {
                result = [item.result];
              }
            }
            option = _.cloneDeep({
              ...option,
              firstMarkUserId: doctorIdList[0],
              approveContent: result as string,
            });
            form[option.approveField] = result;
          };
        });
      // doctorIdList.length !== 0 && (option.firstMarkUserId = doctorIdList[0]);
      break;
    case 2:
      list[0].formComponentList.length !== 0 &&
        list[0].formComponentList.map((item) => {
          if (item.formComponentId === option.id) {
            if (option.type === 'checkbox') {
              if (item.result.includes(',')) {
                let resultArr = item.result.split(',');
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    resultArr.map(t => {
                      if (it.value === t) {
                        item.result = it.label + ',';
                      }
                    })
                  })
                }
              } else {
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    if (it.value === item.result) {
                      item.result = it.label;
                    }
                  })
                }
              }
            }
            if (option.type === 'child_select') {
              if (item.result.includes('@#@')) {
                let resultArr = item.result.split('@#@');
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    resultArr.map(t => {
                      if (it.value === t) {
                        item.result = it.label + ',';
                      }
                    })
                  })
                }
              } else {
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    if (it.value === item.result) {
                      item.result = it.label;
                    }
                  })
                }
              }
            }
            if (option.options && option.options.length !== 0) {
              option.options.map(it => {
                if (it.value === item.result) {
                  item.result = it.label;
                }
              })
            }
            option = _.cloneDeep({
              ...option,
              firstMarkUserId: doctorIdList[0],
              firstMarkContent: item.result,
            });
          };
        });
      list[1].formComponentList.length !== 0 &&
        list[1].formComponentList.map((item) => {
          if (item.formComponentId === option.id) {
            let result = item.result;
            if (option.type === 'checkbox') {
              if (item.result.includes(',')) {
                let resultArr = item.result.split(',');
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    resultArr.map(t => {
                      if (it.value === t) {
                        item.result = it.label + ',';
                      }
                    })
                  })
                }
              } else {
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    if (it.value === item.result) {
                      item.result = it.label;
                    }
                  })
                }
              }
            }
            if (option.type === 'child_select') {
              if (item.result.includes('@#@')) {
                let resultArr = item.result.split('@#@');
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    resultArr.map(t => {
                      if (it.value === t) {
                        item.result = it.label + ',';
                      }
                    })
                  })
                }
              } else {
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    if (it.value === item.result) {
                      item.result = it.label;
                    }
                  })
                }
              }
            }
            if (option.options && option.options.length !== 0) {
              option.options.map(it => {
                if (it.value === item.result) {
                  item.result = it.label;
                }
              })
            }
            option = _.cloneDeep({
              ...option,
              firstMarkUserId: doctorIdList[0],
              approveContent: item.result,
            });
            if (option.firstMarkContent !== '' && option.secondMarkContent !== '') {
              form[option.approveField] = result;
              // 标注医生填写的征象信息逻辑处理
              if (option.type === 'child_select') {
                if (result.includes('@#@')) {
                  form[option.approveField] = result.split('@#@');
                } else {
                  form[option.approveField] = [result];
                }
              }
              if (option.type === 'checkbox') {
                if (result.includes(',')) {
                  form[option.approveField] = result.split(',');
                } else {
                  form[option.approveField] = [result];
                }
              }
            } else {
              form[option.approveField] = result;
              // 标注医生未填写征象信息逻辑处理
              if (option.type === 'child_select') {
                if (result.includes('@#@')) {
                  form[option.approveField] = result.split('@#@');
                } else {
                  form[option.approveField] = [result];
                }
              }
              if (option.type === 'checkbox') {
                if (result.includes(',')) {
                  form[option.approveField] = result.split(',');
                } else {
                  form[option.approveField] = [result];
                }
              }
            }
          };
        });
      doctorIdList.length !== 0 && (option.firstMarkUserId = doctorIdList[0]);
      break;
    case 3:
      list[0].formComponentList.length !== 0 &&
        list[0].formComponentList.map((item) => {
          if (item.formComponentId === option.id) {
            if (option.type === 'checkbox') {
              if (item.result.includes(',')) {
                let resultArr = item.result.split(',');
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    resultArr.map(t => {
                      if (it.value === t) {
                        item.result = it.label + ',';
                      }
                    })
                  })
                }
              } else {
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    if (it.value === item.result) {
                      item.result = it.label;
                    }
                  })
                }
              }
            }
            if (option.type === 'child_select') {
              if (item.result.includes('@#@')) {
                let resultArr = item.result.split('@#@');
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    resultArr.map(t => {
                      if (it.value === t) {
                        item.result = it.label + ',';
                      }
                    })
                  })
                }
              } else {
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    if (it.value === item.result) {
                      item.result = it.label;
                    }
                  })
                }
              }
            }
            if (option.type === 'radiobox') {
              if (option.options && option.options.length !== 0) {
                option.options.map(it => {
                  if (it.value === item.result) {
                    item.result = it.label;
                  }
                })
              }
            }
            option = _.cloneDeep({
              ...option,
              firstMarkUserId: doctorIdList[0],
              firstMarkContent: item.result,
              secondMarkUserId: doctorIdList[1],
            });
          };
        });
      list[1].formComponentList.length !== 0 &&
        list[1].formComponentList.map((item) => {
          if (item.formComponentId === option.id) {
            if (option.type === 'checkbox') {
              if (item.result.includes(',')) {
                let resultArr = item.result.split(',');
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    resultArr.map(t => {
                      if (it.value === t) {
                        item.result = it.label + ',';
                      }
                    })
                  })
                }
              } else {
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    if (it.value === item.result) {
                      item.result = it.label;
                    }
                  })
                }
              }
            }
            if (option.type === 'child_select') {
              if (item.result.includes('@#@')) {
                let resultArr = item.result.split('@#@');
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    resultArr.map(t => {
                      if (it.value === t) {
                        item.result = it.label + ',';
                      }
                    })
                  })
                }
              } else {
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    if (it.value === item.result) {
                      item.result = it.label;
                    }
                  })
                }
              }
            }
            if (option.type === 'radiobox') {
              if (option.options && option.options.length !== 0) {
                option.options.map(it => {
                  if (it.value === item.result) {
                    item.result = it.label;
                  }
                })
              }
            }
            option = _.cloneDeep({
              ...option,
              firstMarkUserId: doctorIdList[0],
              secondMarkUserId: doctorIdList[1],
              secondMarkContent: item.result,
            });
          };
        });
      list[2].formComponentList.length !== 0 &&
        list[2].formComponentList.map((item) => {
          let result = item.result;
          if (item.formComponentId === option.id) {
            if (option.type === 'checkbox') {
              if (item.result.includes(',')) {
                let resultArr = item.result.split(',');
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    resultArr.map(t => {
                      if (it.value === t) {
                        item.result = it.label + ',';
                      }
                    })
                  })
                }
              } else {
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    if (it.value === item.result) {
                      item.result = it.label;
                    }
                  })
                }
              }
            }
            if (option.type === 'child_select') {
              if (item.result.includes('@#@')) {
                let resultArr = item.result.split('@#@');
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    resultArr.map(t => {
                      if (it.value === t) {
                        item.result = it.label + ',';
                      }
                    })
                  })
                }
              } else {
                if (option.options && option.options.length !== 0) {
                  option.options.map(it => {
                    if (it.value === item.result) {
                      item.result = it.label;
                    }
                  })
                }
              }
            }
            if (option.type === 'radiobox') {
              if (option.options && option.options.length !== 0) {
                option.options.map(it => {
                  if (it.value === item.result) {
                    item.result = it.label;
                  }
                })
              }
            }
            option = _.cloneDeep({
              ...option,
              firstMarkUserId: doctorIdList[0],
              secondMarkUserId: doctorIdList[1],
              approveContent: item.result,
            });
            if (option.firstMarkContent !== '' && option.secondMarkContent !== '') {
              form[option.approveField] = result;
              // 标注医生填写的征象信息逻辑处理
              if (option.type === 'child_select') {
                if (result.includes('@#@')) {
                  form[option.approveField] = result.split('@#@');
                } else {
                  form[option.approveField] = [result];
                }
              }
              if (option.type === 'checkbox') {
                if (result.includes(',')) {
                  form[option.approveField] = result.split(',');
                } else {
                  form[option.approveField] = [result];
                }
              }
            } else {
              form[option.approveField] = result;
              // 标注医生未填写征象信息逻辑处理
              if (option.type === 'child_select') {
                if (result.includes('@#@')) {
                  form[option.approveField] = result.split('@#@');
                } else {
                  form[option.approveField] = [result];
                }
              }
              if (option.type === 'checkbox') {
                if (result.includes(',')) {
                  form[option.approveField] = result.split(',');
                } else {
                  form[option.approveField] = [result];
                }
              }
            }
          };
        });
      doctorIdList.length !== 0 && (option.firstMarkUserId = doctorIdList[0]);
      doctorIdList.length !== 0 && (option.secondMarkUserId = doctorIdList[1]);
      break;
    default:
      break;
  }
  return _.cloneDeep(option);
};

export const changeFormAddOption = (options: PHStoreType.FormItem[], list: PHStoreType.LesionListItem[], form: {
  [x: string]: string | string[];
}) => {
  const optionsEnum: {[x: number]: any} = {};
  list.length !== 0 && list[0].formComponentList.map(item => {
    optionsEnum[item.formComponentId] = item;
  });
  options.length !== 0 && options.map(item => {
    const current: PHStoreType.Component = optionsEnum[item.id];
    if (current) {
      form[current.id] = current.result;
      if (current.type === 'checkbox') {
        if (current.result.includes(',')) {
          form[current.id] = current.result.split(',');
        } else {
          form[current.id] = [current.result];
        }
      }
      if (current.type === 'child_select') {
        if (current.result.includes('@#@')) {
          form[current.id] = current.result.split('@#@');
        } else {
          form[current.id] = [current.result];
        }
      }
    }
  });
}

export const resultForForm = (lesionList: PHStoreType.LesionListItem[], viewList: {
  lesionData: PHStoreType.LesionData;
  lesion: {
    signForm: PHStoreType.Sign;
    compList: PHStoreType.Component[];
  };
}) => {
  // 创建金标医生征象结果枚举的字典
  // const optionsResultEnum: {[x: number]: any} = _.cloneDeep({});
  const optionsResultEnum: {[x: number]: any} = {};
  // 创建组id的结果枚举字典
  // const imageGroupList: {[x: number]: any} = _.cloneDeep({});
  const imageGroupList: {[x: number]: any} = {};
  lesionList.length !== 0 && lesionList.map(item => {
    if (item.goldStandard) {
      item.formComponentList.length !== 0 && item.formComponentList.map((it: any) => {
        optionsResultEnum[it.formComponentId] = it.result;
        if (it.type === 'checkbox') {
          if (it.result.includes(',')) {
            optionsResultEnum[it.formComponentId] = it.result.split(',');
          } else {
            if (it.result !== '') {
              optionsResultEnum[it.formComponentId] = [it.result];
            }
          };
        };
        if (it.type === 'child_select') {
          if (it.result.includes('@#@')) {
            optionsResultEnum[it.formComponentId] = it.result.split('@#@');
          } else {
            if (it.result !== '') {
              optionsResultEnum[it.formComponentId] = [it.result];
            }
          };
        };
      });
      // imageGroupList[item.imageGroupId] = _.cloneDeep(optionsResultEnum);
      imageGroupList[item.imageGroupId] = optionsResultEnum;
    }
  });
  // 1. 改变征象form表单数据
  // 当前的form 
  // const currentForm = _.cloneDeep(imageGroupList[+viewList.lesion.signForm.formId]);
  const currentForm = imageGroupList[+viewList.lesion.signForm.formId];
  // viewList.lesion.signForm.form = _.cloneDeep({
  //   ...viewList.lesion.signForm.form,
  //   ...currentForm
  // });
  viewList.lesion.signForm.form = {
    ...viewList.lesion.signForm.form,
    ...currentForm
  };
  // 2. 改变标注医生结果数据，并根据数组长度将当前表单回填结果数据
  viewList.lesion.signForm.formOptions = viewList.lesion.signForm.formOptions.map(item => {
    // item = _.cloneDeep(changeUserResult(lesionList, item, viewList.lesionData, viewList.lesion.signForm.form));
    // return _.cloneDeep(item);
    item = changeUserResult(lesionList, item, viewList.lesionData, viewList.lesion.signForm.form);
    return item;
  });
  // 最终给表单重新赋值
  // viewList.lesion.signForm = _.cloneDeep({
  //   ...viewList.lesion.signForm,
  //   lesionType: viewList.lesionData.lesionType,
  //   firstMarkUserId: viewList.lesionData.firstMarkUserId,
  //   secondMarkUserId: viewList.lesionData.secondMarkUserId,
  //   positionVal: viewList.lesionData.positionVal,
  // });
  viewList.lesion.signForm = {
    ...viewList.lesion.signForm,
    lesionType: viewList.lesionData.lesionType,
    firstMarkUserId: viewList.lesionData.firstMarkUserId,
    secondMarkUserId: viewList.lesionData.secondMarkUserId,
    positionVal: viewList.lesionData.positionVal,
  };
  // return _.cloneDeep({
  //   ...viewList,
  //   lesion: _.cloneDeep({...viewList.lesion})
  // })
  return _.cloneDeep({
    ...viewList,
    lesion: viewList.lesion
  })
}

const changeUserResult = (lesionList: PHStoreType.LesionListItem[], option: PHStoreType.FormItem, lesionData: PHStoreType.LesionData, form: {
  [x: string]: string | string[];
}) => {
  // option.firstMarkUserId = lesionData.firstMarkUserId;
  // option.secondMarkUserId = lesionData.secondMarkUserId;
  let tempResult: {
    firstMarkContent?: string;
    secondMarkContent?: string;
    approveContent?: string;
    type: number;
    formType: string;
    id: number;
  } = _.cloneDeep({}) as {
    firstMarkContent?: string;
    secondMarkContent?: string;
    approveContent?: string;
    type: number;
    formType: string;
    id: number;
  };
  switch (lesionList.length) {
    case 1:
      lesionList[0].formComponentList.length !== 0 && lesionList[0].formComponentList.map(item => {
        if (item.formComponentId === option.id) {
          tempResult.approveContent = item.result;
          tempResult.type = option.lesionType;
          tempResult.formType = option.type;
          tempResult.id = option.id;
          option = _.cloneDeep({
            ...option,
            approveContent: changeResult(item.result, option.type, option),
          });
        };
      });
      break;
    case 2:
      lesionList[0].formComponentList.length !== 0 && lesionList[0].formComponentList.map(item => {
        if (item.formComponentId === option.id) {
          tempResult.firstMarkContent = item.result;
          tempResult.type = option.lesionType;
          tempResult.formType = option.type;
          tempResult.id = option.id;
          option = _.cloneDeep({
            ...option,
            firstMarkContent: changeResult(item.result, option.type, option),
          });
        };
      });
      lesionList[1].formComponentList.length !== 0 && lesionList[1].formComponentList.map(item => {
        if (item.formComponentId === option.id) {
          tempResult.approveContent = item.result;
          tempResult.type = option.lesionType;
          tempResult.formType = option.type;
          tempResult.id = option.id;
          option = _.cloneDeep({
            ...option,
            approveContent: item.result,
          });
        };
      });
      backfillForm(form, option, tempResult, lesionData);
      break;
    case 3:
      lesionList[0].formComponentList.length !== 0 && lesionList[0].formComponentList.map(item => {
        if (item.formComponentId === option.id) {
          tempResult.firstMarkContent = item.result;
          tempResult.type = option.lesionType;
          tempResult.formType = option.type;
          tempResult.id = option.id;
          option = _.cloneDeep({
            ...option,
            firstMarkContent: changeResult(item.result, option.type, option)
          });
        };
      });
      lesionList[1].formComponentList.length !== 0 && lesionList[1].formComponentList.map(item => {
        if (item.formComponentId === option.id) {
          tempResult.secondMarkContent = item.result;
          tempResult.type = option.lesionType;
          tempResult.formType = option.type;
          tempResult.id = option.id;
          option = _.cloneDeep({
            ...option,
            secondMarkContent: changeResult(item.result, option.type, option)
          });
        };
      });
      lesionList[2].formComponentList.length !== 0 && lesionList[2].formComponentList.map(item => {
        if (item.formComponentId === option.id) {
          tempResult.approveContent = item.result;
          tempResult.type = option.lesionType;
          tempResult.formType = option.type;
          tempResult.id = option.id;
          option = _.cloneDeep({
            ...option,
            approveContent: item.result
          });
        };
      });
      backfillForm(form, option, tempResult, lesionData);
      break;
    default:
      break;
  }
  return _.cloneDeep(option);
}

// 通过结果变更成标注医生展示文案
const changeResult = (result: string, type: string, option: PHStoreType.FormItem) => {
  let resultStr = result;
  if (option.type === 'checkbox') {
    let tempArr: string[] = [];
    if (result.includes(',')) {
      let resultArr: string[] = result.split(',');
      if (option.options && option.options.length !== 0) {
        option.options.map(it => {
          resultArr.map(t => {
            if (it.value === t) {
              tempArr.push(it.label);
            }
          })
        })
      }
    } else {
      if (option.options && option.options.length !== 0) {
        option.options.map(it => {
          if (it.value === result) {
            tempArr.push(it.label);
          }
        })
      }
    }
    resultStr = tempArr.join(',');
  }
  if (option.type === 'child_select') {
    let tempArr: string[] = [];
    if (result.includes('@#@')) {
      let resultArr = result.split('@#@');
      if (option.options && option.options.length !== 0) {
        option.options.map(it => {
          resultArr.map(t => {
            if (it.value === t) {
              tempArr.push(it.label);
            }
          })
        })
      }
    } else {
      if (option.options && option.options.length !== 0) {
        option.options.map(it => {
          if (it.value === result) {
            tempArr.push(it.label);
          }
        })
      }
    }
    resultStr = tempArr.join(',');
  }
  if (option.options && option.options.length !== 0) {
    option.options.map(it => {
      if (it.value === result) {
        resultStr = it.label;
      }
    })
  }
  return resultStr;
}

// 将标注医生的结果回填回表单并判定是否需要调用接口
const backfillForm = (form: {[x: string]: string | string[];}, option: PHStoreType.FormItem, result: {
  firstMarkContent?: string;
  secondMarkContent?: string;
  approveContent?: string;
  type: number;
  formType: string;
  id: number;
}, lesionData: PHStoreType.LesionData) => {
  if (result.type === 1 && JSON.stringify(result) !== '{}') {
    // 必须回填数据
    if (lesionData.approveStatus !== 2) {
      if (result.firstMarkContent || result.secondMarkContent) {
        let resultStr: string | string[] | undefined = (result.firstMarkContent || result.secondMarkContent) ?? '';
        if (result.formType === 'checkbox') {
          if ((result.firstMarkContent && result.firstMarkContent.includes(',')) || (result.secondMarkContent && result.secondMarkContent.includes(','))) {
            resultStr = (result.firstMarkContent && result.firstMarkContent.split(',')) || (result.secondMarkContent && result.secondMarkContent.split(','));
          } else {
            result.firstMarkContent && (resultStr = [result.firstMarkContent]) || result.secondMarkContent && (resultStr = [result.secondMarkContent]);
          };
        };
        if (result.formType === 'child_select') {
          if ((result.firstMarkContent && result.firstMarkContent.includes('@#@')) || (result.secondMarkContent && result.secondMarkContent.includes('@#@'))) {
            resultStr = (result.firstMarkContent && result.firstMarkContent.split('@#@')) || (result.secondMarkContent && result.secondMarkContent.split('@#@'));
          } else {
            result.firstMarkContent && (resultStr = [result.firstMarkContent]) || result.secondMarkContent && (resultStr = [result.secondMarkContent]);
          };
        };
        form[result.id] = resultStr ?? '';
      };
    };
  };
  if (result.type === 2 && JSON.stringify(result) !== '{}') {
    // 判定两个标注医生结果是否相同，相同回填数据
    if (lesionData.approveStatus !== 2) {
      if (result.firstMarkContent && result.secondMarkContent) {
        if (result.firstMarkContent === result.secondMarkContent) {
          let resultStr: string | string[] = result.firstMarkContent;
          if (result.formType === 'checkbox') {
            if (result.firstMarkContent.includes(',')) {
              resultStr = result.firstMarkContent.split(',');
            } else {
              resultStr = [result.firstMarkContent];
            };
          };
          if (result.formType === 'child_select') {
            if (result.firstMarkContent.includes('@#@')) {
              resultStr = result.firstMarkContent.split('@#@');
            } else {
              resultStr = [result.firstMarkContent];
            };
          };
          form[result.id] = resultStr;
        };
      };
    };
  };
  if (result.type === 3 && JSON.stringify(result) !== '{}') {
    // 必须回填数据
    if (lesionData.approveStatus !== 2) {
      if (result.firstMarkContent) {
        let resultStr: string | string[] = result.firstMarkContent;
        if (result.formType === 'checkbox') {
          if (result.firstMarkContent.includes(',')) {
            resultStr = result.firstMarkContent.split(',');
          } else {
            resultStr = [result.firstMarkContent];
          };
        };
        if (result.formType === 'child_select') {
          if (result.firstMarkContent.includes('@#@')) {
            resultStr = result.firstMarkContent.split('@#@');
          } else {
            resultStr = [result.firstMarkContent];
          };
        };
        form[result.id] = resultStr;
      };
    };
  };

};

const changeListResult = (formComponentList: ApiType.FormComponentList[], option: PHStoreType.FormItem, type: keyof PHStoreType.FormItem) => {
  formComponentList.length !== 0 && formComponentList.map(item => {
    if (item.formComponentId === option.id) {
      option = _.cloneDeep({
        ...option,
      });
      // option[type] = item.result;
    }
  })
  return _.cloneDeep(option);
}

export const addViewList = (dataList: PHStoreType.LesionListItem[][], resultList: {
  lesionData: PHStoreType.LesionData;
  lesion: {
    signForm: PHStoreType.Sign;
    compList: PHStoreType.Component[];
  };
}[], lesionMap: Map<
string,
{
  signForm: PHStoreType.Sign;
  compList: PHStoreType.Component[];
}
>) => {
  let currentList = dataList[dataList.length - 1];
  let result = _.cloneDeep({}) as {
    lesionData: PHStoreType.LesionData;
    lesion: {
      signForm: PHStoreType.Sign;
      compList: PHStoreType.Component[];
    };
  };
  result.lesionData = _.cloneDeep({
    firstLesionCode: '',
    firstLesionName: '',
    firstLesionId: 0,
    firstMarkUserId: 0,
    secondLesionCode: '',
    secondLesionName: '',
    secondLesionId: 0,
    secondMarkUserId: 0,
    approveLeisonCode: currentList[0].lesion,
    approveLeisonName: currentList[0].name,
    approveLeisonId: currentList[0].imageId,
    approveUserId: currentList[0].doctorId,
    toolType: currentList[0].imageAnnotationToolType,
    uuid: currentList[0].uuid || getRandomString(),
    color: '#f7bc5a',
    positionVal: currentList[0].expectResultType,
    lesionType: currentList[0].consistencyType,
    approveStatus: currentList[0].auditStatus ?? 1,
    imageResult: currentList[0].imageResult,
    isApproveEye: true,
    isCurrent: false,
    imageGroupId: currentList[0].imageGroupId,
    className:
      currentList[0].goldStandard && currentList[0].consistencyType === 4
        ? 'approve'
        : '',
  });
  const lesion = _.cloneDeep(lesionMap.get(currentList[0].lesion)) as {
    signForm: PHStoreType.Sign;
    compList: PHStoreType.Component[];
  };
  lesion.signForm.formId = result.lesionData.imageGroupId;
  lesion.signForm.formOptions = lesion.signForm.formOptions && lesion.signForm.formOptions.map((it) => {
    it.lesionType = result.lesionData.lesionType;
    return it;
  });
  lesion.signForm = _.cloneDeep({
    ...lesion.signForm,
    lesionType: result.lesionData.lesionType,
    firstMarkUserId: result.lesionData.firstMarkUserId,
    secondMarkUserId: result.lesionData.secondMarkUserId,
    positionVal: result.lesionData.positionVal,
  });
  result.lesion = _.cloneDeep({...lesion});
  resultList.push(reactive(result));
  return resultList;
}